package com.wpp.handler;

import com.wpp.protocol.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * @author by wpp25
 * @Classname UserServiceHandler
 * @Description  自定义的业务处理器
 * @Date 2020/11/25 20:54
 */
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter {


    private ApplicationContext applicationContext;
    private Integer port;

    public UserServiceHandler(ApplicationContext applicationContext,Integer port) {
        this.applicationContext = applicationContext;
        this.port = port;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        System.out.println(rpcRequest);
        String className = rpcRequest.getClassName();
        Class<?> aClass = Class.forName(className);

        Object bean = applicationContext.getBean(aClass);
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();

        Method declaredMethod = aClass.getDeclaredMethod(methodName, parameterTypes);

        Object invoke = declaredMethod.invoke(bean, parameters);

        ctx.writeAndFlush(invoke.toString() +" 端口号为： " + port);
    }
}
